package com.codedef;

import com.codedef.service.UserService;
import io.helidon.config.Config;
import io.helidon.media.jsonp.server.JsonSupport;
import io.helidon.webserver.Routing;
import io.helidon.webserver.ServerConfiguration;
import io.helidon.webserver.WebServer;


public class Main {

    public static void main(String[] args) {
        startServer();
    }

    /**
     * 服务启动相关逻辑
     */
    private static void startServer() {
        // 加载配置
        Config config = Config.create();
        ServerConfiguration serverConfig = ServerConfiguration.create(config.get("server"));

        // 创建WebServer
        WebServer webServer = WebServer.create(serverConfig, createRouting());

        // 启动服务
        webServer.start()
                .thenAccept(ws -> {
                    System.out.println("服务启动成功 http://localhost:" + ws.port());
                    ws.whenShutdown().thenRun( () -> {
                        System.out.println("服务已关闭");
                    } );
                })
                .exceptionally(t -> {
                    System.out.println("服务启动失败");
                    t.printStackTrace(System.err);
                    return null;
                });

    }

    /**
     * 生成路由表，将路由与service实例进行绑定
     * @return
     */
    private static Routing createRouting() {
        // 实例化各个Service
        UserService userService = new UserService();

        // 创建路由
        Routing routing = Routing.builder()
                .register(JsonSupport.create())
                .register("/user", userService).build();
        return routing;
    }

}
